package com.carkeeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.DepartmentDTO;
import com.carkeeper.mapper.DepartmentMapper;
import com.carkeeper.pojo.DepartmentPO;
import com.carkeeper.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public boolean create(DepartmentPO departmentPO) {
        return departmentMapper.insert(departmentPO) > 0;
    }

    @Override
    public boolean update(DepartmentPO departmentPO) {
        return departmentMapper.updateById(departmentPO) > 0;
    }

    @Override
    public boolean delete(long departmentId) {
        return departmentMapper.deleteById(departmentId) > 0;
    }

    @Override
    public Page<DepartmentPO> query(String code, String name, long page, long pageSize) {
        Page<DepartmentPO> pageResult = new Page<>(page, pageSize);
        LambdaQueryWrapper<DepartmentPO> wrapper = new LambdaQueryWrapper<>();

//        wrapper.eq("code",code)
//                .eq("name",name);
        if (!StringUtils.isEmpty(code)) {
            wrapper.like(DepartmentPO::getCode, code);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like(DepartmentPO::getName, name);
        }

        return departmentMapper.selectPage(pageResult, wrapper);
    }

    @Override
    public boolean has(String code) {
        QueryWrapper<DepartmentPO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(DepartmentPO::getCode, code);

        return departmentMapper.selectCount(wrapper) > 0;
    }

    @Override
    public DepartmentPO getById(Long id) {
        return departmentMapper.selectById(id);
    }

    @Override
    public List<DepartmentDTO> findAll(List<Long> ids) {
        List<DepartmentDTO> results = new ArrayList<>();
        LambdaQueryWrapper<DepartmentPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            lambdaQueryWrapper.in(DepartmentPO::getId, ids);
        }
        List<DepartmentPO> poList = departmentMapper.selectList(lambdaQueryWrapper);
        if (poList != null && poList.size() > 0) {
            poList.forEach(po -> {
                DepartmentDTO dto = new DepartmentDTO();
                dto.setCode(po.getCode());
                dto.setId(po.getId());
                dto.setName(po.getName());
                results.add(dto);
            });
        }
        return results;
    }
}
